<template>
  <view :class="theme" style="padding-bottom: 160rpx;">

    <view v-if="cart.list.length" @click="manageItems" hover-class="op-[0.6]" class="m-30 text-28 fw-700 items-end">
      {{ enabledManage ? "退出" : "" }}管理
    </view>

    <view v-for="(item, index) in cart.list" :key="index" class="bg-section b-rounded-16 flex-row items-center"
      style="padding: 16rpx 24rpx; margin: 0 30rpx 30rpx;">
      <switch @change="changeCheckbox(index, $event)" :checked="Boolean(item.goods_data?.checked)"
        :color="$config.COLOR_PRIMARY" type="checkbox" />
      <view @click="uniNavigator({ url: `/pages/client/mall/goodsInfo?sn=${item.goods_data?.goods_sn}` })"
        class="ml-18 flex-1 flex-row overflow-hidden">
        <uv-image radius="8" width="160" height="160" :src="include(item.goods_img)" />
        <view class="flex-1 ml-24 justify-between overflow-hidden">
          <text class="text-28 ellipsis">{{ item.goods_name || "-" }}</text>
          <label class="mt-12 color-placeholder fw-400">
            <text class="flex-1 color-placeholder ellipsis">{{ item.spec_text || "-" }}</text>
            <text class="color-base">× {{ item.goods_data.num || 0 }}</text>
          </label>

          <label class="mt-12 items-baseline">
            <text class="text-40 color-primary">{{ Number(item.price || 0).toFixed(2) }}</text>
          </label>
        </view>
      </view>
    </view>

    <view v-if="cart.list.length"
      style="bottom: var(--window-bottom); left: var(--window-left); right: var(--window-right);"
      class="fixed content-box items-center justify-between h-80 pt-40 pb-40 flex-row bg-section text-28">
      <label class="ml-30">
        <switch :checked="isAllChecked" :color="$config.COLOR_PRIMARY" type="checkbox" @change="allChecked" />
        <text class="text-28">全选</text>
      </label>
      <view v-if="!enabledManage" class="flex-1 flex-row items-center">
        <label class="flex-1 justify-end">
          <text class="text-32">合计：</text>
          <text class="color-primary fw-600 text-36">
            <text>{{ Number(cart.summation || 0).toFixed(2) }}</text>
            <!-- <text>元</text> -->
          </text>
        </label>

        <button hover-class="op-[0.6]" class="bg-primary text-28 pl-30 pr-30 b-rounded-44 color-base ml-40 mr-20"
          @click="settlement" style="line-height: 80rpx; width: 180rpx">
          结算({{ checkedItems.length }})
        </button>
      </view>

      <button v-else hover-class="op-[0.6]" class="bg-13 text-28 pl-30 pr-30 b-rounded-44 color-base ml-40 mr-20"
        @click="removeItems" style="line-height: 80rpx; width: 180rpx;">
        删除({{ checkedItems.length }})
      </button>
    </view>
    <uv-empty v-if="!cart.list.length" margin-top="200" mode="car" text-color="#9b9b9b" />
  </view>
</template>

<script lang="ts" setup>
import { useMapState, math } from "@/common/libs/store";
import { uniNavigator } from "@/common/libs/utils";
import { onShow } from "@dcloudio/uni-app";
import { computed, reactive, ref } from "vue";
import { useStore } from "vuex";

const { theme, shoppingCart } = useMapState(["theme", "shoppingCart"]);
const { $config = {} } = getApp().globalData || {};
const store = useStore();

const enabledManage = ref(false);
const cart = reactive({
  list: [] as any[],
  summation: 0,
});

const checkedItems = computed(() => cart.list.filter(item => item.goods_data.checked));

const manageItems = () => {
  enabledManage.value = !enabledManage.value;
}

const isAllChecked = computed((): boolean => (
  Boolean(cart.list.length) &&
  cart.list.every((item: AnyObject) => item.goods_data.checked)
));

onShow(() => {
  getCartData();
});

const getCartData = () => {
  if (!shoppingCart.value.length) {
    cart.list = [];
    return;
  }
  uni.request({
    url: "/goodsCart",
    data: { goods_data: JSON.stringify(shoppingCart.value) },
    success({ data }: any) {
      cart.list = data;
      store.commit("setState", {
        key: "shoppingCart",
        value: data.map((item: any) => item.goods_data)
      });
      getSummation();
    }
  });
}

const getSummation = () => {
  if (!checkedItems.value.length) {
    cart.summation = 0;
    return;
  }
  cart.summation = math.evaluate(checkedItems.value.map(item =>
    math.evaluate(`${item.price || 0} * ${item.goods_data.num || 0}`)).join("+"));
}

const changeCheckbox = (index: number, { detail }: AnyObject) => {
  cart.list[index].goods_data.checked = detail.value;
  store.commit("setState", {
    key: "shoppingCart",
    value: cart.list.map((item: any) => item.goods_data)
  });
  getSummation();
}

const allChecked = ({ detail }: AnyObject) => {
  store.commit("setState", {
    key: "shoppingCart",
    value: cart.list.map((item: any) => {
      item.goods_data.checked = detail.value;
      return item.goods_data;
    })
  });
  getSummation();
}

const settlement = () => {
  if (!checkedItems.value.length) {
    uni.showToast({ title: "暂未选中商品", icon: "none" });
    return;
  }
  store.commit("setState", {
    key: "confirmOrder",
    value: checkedItems.value.map(item => item.goods_data)
  });

  uni.navigateTo({ url: `/pages/client/mall/confirmOrder` });
}

const removeItems = async () => {
  if (!checkedItems.value.length) {
    uni.showToast({ title: "暂未选中商品", icon: "none" });
    return;
  }

  const { cancel } = await uni.showModal({
    title: "提示",
    content: "确定要删除选中的商品吗？"
  }) as any;

  if (cancel) return;
  cart.list = cart.list.filter(item => !item.goods_data.checked);

  store.commit("setState", {
    key: "shoppingCart",
    value: cart.list.map((item: any) => (item.goods_data))
  });
}

</script>

<style lang="scss" scoped>
// scss
::v-deep {

  switch {
    transform: scale(0.7);

    .wx-checkbox-input,
    .uni-checkbox-input {

      &:empty,
      &.wx-checkbox-input-checked,
      &.uni-checkbox-input-checked {
        border-color: $uni-bg-color-primary;
        background-color: transparent;
      }

      &:not(:empty) {
        border-color: $uni-color-primary;
        background: transparent;
      }

      border-width: 2px;
      border-radius: 50%;
    }


    &:not([disabled]) {

      .wx-checkbox-input:hover,
      .uni-checkbox-input:hover {
        border-color: $uni-bg-color-primary;
      }
    }
  }
}
</style>